package web.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * Created by Administrator on 2017/11/16.
 */
@WebServlet("/imgCode.jpg")
public class IdentifyCode extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int WIDTH=100,HEIGHT=30;
        //在内存中绘制了一个图片
        BufferedImage bufferedImage=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
            Graphics g=bufferedImage.getGraphics();

       // g.setColor(Color.getHSBColor(0,0,0));//将画笔设置为白色
        g.fillRect(0,0,WIDTH,HEIGHT); //填充矩形
        //随机数
        String code=this.generateCode();
        //将这个生成的随机数保存到session中，用来与用户提交的验证码对比
        req.getSession().setAttribute("IMAGE_CODE",code);

        g.setColor(Color.gray);//将画笔设置为蓝颜色
        g.setFont(new Font(null,Font.BOLD,20));//设置字体
        g.drawString(code,8,23);
        //response对象使用输出流ServletOutputStream将数据写入到客户单浏览器

        ServletOutputStream sos= resp.getOutputStream();
        ImageIO.write(bufferedImage,"png",sos);//将绘制完的图形通过ServletOutputStream输出流打印到客户端
        sos.close();
    }



    /**
     * 产生随机数
     * @return
     */
    private String generateCode(){
        String str="0123456789ABCDEFGHIJKLMNOPQRSTUVWZYZ";
        StringBuilder sb=new StringBuilder();
        Random r=new Random(System.currentTimeMillis());
        for(int i=0;i<6;i++){
            int index=r.nextInt(str.length());
            sb.append(str.charAt(index));
        }
        return sb.toString();
    }
}
